
/**
 * @file main
 *
 */
#include <string.h>
#include "home_ui.h"
#include "main.h"
//void btn_exit_event_cb(lv_obj_t * btn_exit, lv_event_t event,void *param);
char *str_path = "";

static pthread_t fevdev_tid;
static pthread_mutex_t fevdev_lock;

// 动态增加数组大小并追加字符串的示例函数（需要额外的逻辑来处理内存分配）
void append_if_not_found_dynamic(char ***arr, int *size, const char *to_append, const char *to_find) {
    int found = 0;
    for (int i = 0; i < *size; i++) {
        if (strstr((*arr)[i], to_find) != NULL) {
            found = 1;
            break;
        }
    }
    if (!found) {
        // 如果没有找到，动态增加数组大小并追加字符串（这里仅为示例，实际实现会更复杂）
        *arr = (char **)realloc(*arr, (*size + 1) * sizeof(char *)); // 重新分配内存以增加一个元素
        if (*arr != NULL) { // 检查realloc是否成功
            (*arr)[*size] = malloc(strlen(to_append) + 1); // 为新元素分配内存
            strcpy((*arr)[*size], to_append); // 复制字符串到新位置
            (*size)++; // 更新数组大小
        } else {
            // 处理内存分配失败的情况...
        }
    }
}
// 假设我们有以下函数来追加字符串（如果需要的话）
void append(char *arr[], int size, const char *str) {
    int found = 0;
    for (int i = 0; i < size; i++) {
        if (strstr(arr[i], str) != NULL) {
            found = 1;
            break;
        }
    }
    if (found) {
        printf("found");
    }else{
        printf("nofound");
    }
    /*
    if (!found) {
        // 如果没有找到，追加字符串
        for (int i = 0; i < size; i++) {
            if (arr[i][0] == '\0') { // 找到第一个空字符串，即可以追加的位置
                strcat(arr[i], to_append); // 追加字符串
                break;
            }
        }
    }
    */
}

static void *file_thread(void *arg)
{
    // 示例：创建一个字符串数组并初始化
    char *arr[5] = {"Hello", "World", "", "", ""}; // 确保至少有一个空字符串用于追加
    const char *to_append = "Example";
    const char *to_find = "World";
    // 检查并追加
    append(arr, 5, to_append);
    // 打印结果以验证
    for (int i = 0; i < 5; i++) {
        printf("%s\n", arr[i]);
    }
    printf("in thread!\n");
}


void rk_desk_init(void){
    static lv_coord_t col_dsc[] = {70, 70, 70, LV_GRID_TEMPLATE_LAST};
    static lv_coord_t row_dsc[] = {50, 50, 50, LV_GRID_TEMPLATE_LAST};

    lv_obj_t * cont = lv_obj_create(lv_scr_act());
    lv_obj_set_grid_dsc_array(cont,col_dsc, row_dsc);
    lv_obj_set_size(cont, 480, 320);
    lv_obj_set_layout(cont, LV_LAYOUT_GRID);

    lv_obj_t * label;
    lv_obj_t * obj;

    uint32_t i;
    DIR *dir;
    struct dirent *entry;
    struct stat fileStat;
    str_path ="/data";
    dir = opendir(str_path);
    if (dir == NULL) {
        perror("opendir");
        return ;
    }
    i=0;
    while ((entry = readdir(dir)) != NULL) {
        if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))continue;
        uint8_t col = i % 3; uint8_t row = i / 3;
        char fullPath[1024];
        snprintf(fullPath, sizeof(fullPath), "%s/%s", str_path, entry->d_name);
        printf("fullPath address:%d,sizeof: %d path:%s\n" ,fullPath,sizeof(fullPath),fullPath);


        if (stat(fullPath, &fileStat) < 0) {
            perror("Failed to get file status");
            continue;
        }
        if (S_ISDIR(fileStat.st_mode)) {
            if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
                printf("Directory: %s\n", fullPath);
            }
        } else if (S_ISREG(fileStat.st_mode)) {
            //printf("File: %s\n", fullPath);
            lv_obj_t * label;
            lv_obj_t * obj;
            obj = lv_btn_create(cont);
            lv_obj_set_grid_cell(obj, LV_GRID_ALIGN_STRETCH, col, 1,LV_GRID_ALIGN_STRETCH, row, 1);

            label = lv_label_create(obj);
            lv_label_set_text_fmt(label, (char *)entry->d_name);
            lv_obj_center(label);
            //const char * user_message = (char *)entry->d_name;
            //const char user_message[] = "Hello, LVGL!";//这样子不行
            const char *user_message =*fullPath;//这样子行 问题出在那
            //const char *user_message = "a.py";//这样子行 问题出在那
            lv_obj_add_event_cb(obj, btn_exit_event_cb, LV_EVENT_CLICKED, (void *)user_message);
            i++;
        } else {
            printf("Other: %s\n", fullPath);
        }
    }
    closedir(dir);
    pthread_create(&fevdev_tid, NULL, file_thread, NULL);
}

void btn_exit_event_cb(lv_event_t * e){
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t * btn = lv_event_get_target(e);
    char *user_data =lv_event_get_user_data(e);

    //obj->spec_attr->event_dsc[obj->spec_attr->event_dsc_cnt];
    //void * user_data = lv_event_get_user_data(e);
    if(user_data  != NULL) {
        printf("User data0: %d\n", user_data );
        //printf("User data0: %d\n", *user_data );
        printf("User data0: %d\n", *(&user_data));
        printf("User data0: %d\n", &user_data);
        printf("User data0: %d\n", &user_data+0x1);
        printf("User data0: %d\n", *(&user_data+1));
        //printf("User data1: %s\n", user_data);
        //char *dest = malloc(strlen((str_path)+ strlen(user_data)+1) * sizeof(char)); 
        //getfilename(dest,user_data); 
        //exec_comand(dest);
        //free(dest); // 释放内存
    }
}

void exec_comand(char *file){
    FILE *fp;
    char path[1035];
    char *exec="python3 ";
    char *comand = malloc(strlen((exec)+ strlen(file)+1) * sizeof(char)); 
    strcpy(comand, exec);
    strcat(comand, file); 
    fp = popen(comand, "r");
    if (fp == NULL) {
        perror("popen failed");
        return ;
    }
    while (fgets(path, sizeof(path), fp) != NULL) {
        printf("%s", path); // 打印输出结果
    }
    pclose(fp); // 关闭管道并等待子进程结束
}